package com.yonyou.pmclouds.basecom.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonyou.iuap.tenant.sdk.UserCenter;
import com.yonyou.pmclouds.basecom.conf.TrialInfoProperties;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.view.BuziExWrapObject;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@Slf4j
public class TrialInterceptor implements HandlerInterceptor {


    private TrialInfoProperties trialInfoProperties;

    private ObjectMapper mapper = new ObjectMapper();

    public TrialInterceptor(TrialInfoProperties trialInfoProperties){
        this.trialInfoProperties = trialInfoProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        String loginUserId = RuntimeEnvironment.getLoginUserId();

        if(loginUserId == null || "".equals(loginUserId)){
            log.error("请登录");
            errMsgShow(response,"noLogin","未登录");
            return false;
        }

        boolean isAdmin = false;
        Map<String,Object> userInfoMap = null;
        List<Map> userList = null;
        for (String adminEmail:trialInfoProperties.getAdmin_email()) {
            String userInfo = UserCenter.getUserByContact(adminEmail,"email");
            userInfoMap = mapper.readValue(userInfo, Map.class);
            userList = ((List<Map>)(userInfoMap.get("users")));
            if(userList == null || userList.size() == 0)
                continue;

            for(Map adminMap :userList ){
                if(loginUserId.equals(adminMap.get("userId")))
                    isAdmin = true;
            }

        }

        if(!isAdmin){
            log.error("该用户没有试用信息管理权限");
            errMsgShow(response,"noAuth","该用户没有试用信息管理权限");
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    /**
     * 错误信息返回
     *
     * @param response
     * @param resultCode
     * @param resultMsg
     * @throws IOException
     */
    private void errMsgShow(ServletResponse response, String resultCode, String resultMsg) throws IOException {

        JSONObject errResult = JSONObject
                .fromObject(new BuziExWrapObject(resultCode,resultMsg));

        PrintWriter writer = response.getWriter();
        writer.write(errResult.toString());

    }
}
